import React from 'react';
import { Dropdown, Icon, Button, Input, Tree, Avatar, Empty } from 'antd';
import cn from 'classnames';
import _ from 'lodash';
import xss from 'xss';
import { employeeList, companyGettree } from '@/services/Organization/staffmanage';
import styles from './EmployeeSelect.less';

const { TreeNode } = Tree;

const getKey = ({ companyId = '', departmentId = '', id = '' }) => {
    if (departmentId) {
        return `${companyId}-${departmentId}-${id}`;
    }
    return `${companyId}-${id === companyId ? '' : id}`;
};

const EmployeeSelect = ({ title, placeholder, maxCount, style, onOk, onCancel }) => {
    const [tab, setTab] = React.useState(2);
    const [finalTree, setFinalTree] = React.useState([]);
    // console.log('EmployeeSelect -> finalTree', finalTree);
    const [companyTree, setCompanyTree] = React.useState([]);
    const [tempEmployeeList, setTempEmployeeList] = React.useState([]);
    const [recentList, setRecentList] = React.useState([]);
    // console.log('EmployeeSelect -> recentList', recentList);
    const [searchList, setSearchList] = React.useState([]);
    const [selectedKeys, setSelectedKeys] = React.useState([]);
    const [expandedKeys, setExpandedKeys] = React.useState([]);
    const [employeeObj, setEmployeeObj] = React.useState(null);
    // console.log('EmployeeSelect -> employeeObj', employeeObj);
    const [result, setResult] = React.useState([]);
    const totalObjRef = React.useRef({});
    // console.log('EmployeeSelect -> totalObjRef', totalObjRef.current);
    const tabRef = React.useRef(2);
    const searchRef = React.useRef('');
    const hideRef = React.useRef(false);
    const keysRef = React.useRef([]);
    // const itemRef = React.useRef([]);

    const getResultTreeKeys = arr => {
        if (arr && arr.length > 0) {
            arr.forEach(item => {
                keysRef.current.push(item.key);
                if (item.children) {
                    getResultTreeKeys(item.children);
                }
            });
        }
    };

    // const getItemChildren = arr => {
    //     if (arr && arr.length > 0) {
    //         arr.forEach(item => {
    //             if (!item.isGroup) {
    //                 itemRef.current.push(item);
    //             }
    //             if (item.children) {
    //                 getItemChildren(item.children);
    //             }
    //         });
    //     }
    // };

    const getResultKeys = () => {
        console.log(result);
        getResultTreeKeys(result);
        console.log(keysRef.current);
        const arr = [...keysRef.current];
        keysRef.current = [];
        // return result.map(item => item.key);
        return arr;
    };

    const getCompanyTree = async () => {
        const res = await companyGettree({ permissionUrl: 'office:orgs:employee' });
        // console.log(res);
        const { code, data = [] } = res;
        if (code === 10000) {
            setCompanyTree(data);
        }
    };

    const getFinalTree = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => {
                const tempKey = `${item.companyId}-${item.id === item.companyId ? '' : item.id}`;
                const { children = [] } = item;
                let tempChildren = [];
                if (children.length > 0) {
                    tempChildren = getFinalTree(children) || [];
                }
                if (employeeObj && employeeObj[tempKey]) {
                    tempChildren = tempChildren.concat(employeeObj[tempKey]);
                }
                totalObjRef.current = {
                    ...totalObjRef.current,
                    [tempKey]: {
                        ...item,
                        key: tempKey,
                        isGroup: true,
                        children: tempChildren
                    }
                };
                return {
                    ...item,
                    key: tempKey,
                    isGroup: true,
                    children: tempChildren
                };
            });
        }
        return null;
    };

    const getEmployeeList = async ({ companyId = 100, departmentId }) => {
        const res = await employeeList({ companyId, departmentId, pageSize: 99999 });
        // console.log(res);
        const {
            code,
            data: { rows = [] }
        } = res;
        if (code === 10000) {
            const obj = {};
            const tempList = rows.map(item => {
                totalObjRef.current = {
                    ...totalObjRef.current,
                    [getKey(item)]: {
                        ...item,
                        key: getKey(item)
                    }
                };
                return {
                    ...item,
                    key: getKey(item)
                };
            });
            setTempEmployeeList(tempList);
            // console.log('getEmployeeList -> tempList', tempList);
            setRecentList(tempList);
            tempList.forEach(item => {
                const tempKey = `${item.companyId}-${item.departmentId || ''}`;
                if (obj[tempKey]) {
                    obj[tempKey].push(item);
                } else {
                    obj[tempKey] = [item];
                }
            });
            setEmployeeObj(obj);
        }
    };

    const handleRemove = (item, index) => () => {
        console.log(item, index);
        const temp = [].concat(result);
        temp.splice(index, 1);
        setResult(temp);
    };

    const handleVisibleChange = visible => {
        console.log(visible);
        if (!visible) {
            // setResult([]);
            setTab(2);
        }
    };

    const handleOk = () => {
        hideRef.current = true;
        // console.log(result);
        const employeeIds = result.map(item => item.employeeCode);
        onOk({ employeeIds, employeeItems: result });
        handleVisibleChange(false);
    };

    const handleCancel = () => {
        hideRef.current = true;
        onCancel();
        handleVisibleChange(false);
    };

    const getSearchList = _.debounce(value => {
        searchRef.current = value;
        if (value) {
            if (tab !== 3) {
                tabRef.current = tab;
            }
            setTab(3);
            const keys = getResultKeys();
            setSearchList(
                tempEmployeeList
                    .filter(item => item.employeeName.indexOf(value) !== -1)
                    .map(item => ({
                        ...item,
                        isSelected: keys.includes(item.key)
                    }))
            );
            return;
        }
        setTab(tabRef.current);
        setSearchList([]);
    }, 200);

    const handleSearch = e => {
        // if (e.target.value) {
        getSearchList(e.target.value);
        //     return;
        // }
        // setTab(tabRef.current);
        // setSearchList([]);
    };

    const renderIcon = ({ selected }, item) => {
        if (item.isGroup) {
            return null;
        }
        if (selected) {
            return <i className="icon iconfont iconwancheng" style={{ fontSize: 14, color: '#FFA22D' }} />;
        }
        return <i className="icon iconfont iconyuan" style={{ fontSize: 14, color: '#D9D9D9' }} />;
    };

    const getTreeNode = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <TreeNode
                    title={`${item.employeeName || item.name}`}
                    key={getKey(item)}
                    icon={e => renderIcon(e, item)}
                    dataRef={item}
                >
                    {getTreeNode(item.children || [])}
                </TreeNode>
            ));
        }
        return null;
    };

    const handleTreeSelect = (keys, { selected, node, selectedNodes, event }) => {
        console.log('handleTreeSelect -> selectedKeys', keys);
        console.log('handleTreeSelect -> selected', selected);
        console.log('handleTreeSelect -> node', node);
        console.log('handleTreeSelect -> nodedataref', node.props.dataRef);
        console.log('handleTreeSelect -> selectedNodes', selectedNodes);
        console.log('handleTreeSelect -> event', event);
        const {
            props: { eventKey }
        } = node;
        console.log('handleTreeSelect -> eventKey', eventKey);
        const nowItem = totalObjRef.current[eventKey];
        console.log(nowItem);
        if (selected) {
            if (nowItem.isGroup) {
                console.log('部门或公司');
                // getItemChildren(nowItem.children);
                // const tempList = [...itemRef.current];
                // itemRef.current = [];
                // console.log('handleTreeSelect -> tempList', tempList);
                // setResult([...result, ...tempList]);
                if (expandedKeys.indexOf(eventKey) !== -1) {
                    setExpandedKeys(expandedKeys.filter(temp => temp !== eventKey));
                    return;
                }
                setExpandedKeys([...expandedKeys, eventKey]);
                return;
            }
            console.log('员工');
            setResult([...result, nowItem]);
            return;
        }
        console.log('取消');
        if (nowItem.isGroup) {
            console.log('取消部门或公司');
            // setResult(result.filter(temp => temp.key !== nowItem.key));
            setExpandedKeys(expandedKeys.filter(temp => temp !== eventKey));
            return;
        }
        console.log('取消员工');
        const tempArr = result.filter(temp => temp.key !== nowItem.key);
        if (tempArr.length === result.length) {
            return;
        }
        setResult(result.filter(temp => temp.key !== nowItem.key));
    };

    const handleTreeExpand = k => {
        console.log(k);
        setExpandedKeys(k);
    };

    const handleItemClick = (item, index) => () => {
        console.log(item, index);
        const { isSelected = false } = item;
        // if (!isSelected && maxCount && result.length >= maxCount) {
        //     return;
        // }
        if (maxCount && result.length >= maxCount) {
            return;
        }
        const obj = { ...item, isSelected: !isSelected };
        // const arr = [...recentList];
        // arr.splice(index, 1, obj);
        if (isSelected) {
            setResult(result.filter(temp => temp.key !== item.key));
        } else {
            setResult([...result, obj]);
        }
        // setRecentList(arr);
    };

    React.useEffect(() => {
        const keys = getResultKeys();
        console.log('keys', keys);
        setSelectedKeys(keys);
        setRecentList(
            recentList.map(item => ({
                ...item,
                isSelected: keys.includes(item.key)
            }))
        );
        setSearchList(
            searchList.map(item => ({
                ...item,
                isSelected: keys.includes(item.key)
            }))
        );
    }, [result]);

    React.useEffect(() => {
        const tree = getFinalTree(companyTree);
        console.log('tree', tree);
        setFinalTree(tree);
    }, [companyTree, employeeObj]);

    React.useEffect(() => {
        getCompanyTree();
        getEmployeeList({});
    }, []);

    const renderRecent = (arr, tip, val) => {
        if (arr && arr.length > 0) {
            return arr.map((item, index) => {
                let str = item.employeeName;
                if (val) {
                    str = item.employeeName.replace(searchRef.current, `<span>${searchRef.current}</span>`);
                }
                return (
                    <div
                        key={item.id}
                        className={cn(styles.recentItem, { [styles.disabled]: maxCount && result.length >= maxCount })}
                        onClick={handleItemClick(item, index)}
                    >
                        <Avatar icon="user" style={{ marginRight: 6 }} />
                        {/* eslint-disable-next-line react/no-danger */}
                        <div className={styles.recentName} dangerouslySetInnerHTML={{ __html: xss(str) }}></div>
                        {item.isSelected ? (
                            <i className="icon iconfont iconwancheng" style={{ fontSize: 14, color: '#FFA22D' }} />
                        ) : (
                            <i className="icon iconfont iconyuan" style={{ fontSize: 14, color: '#D9D9D9' }} />
                        )}
                    </div>
                );
            });
        }
        return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={tip || ''}></Empty>;
    };

    const renderTree = () => (
        <Tree
            showIcon
            multiple
            // defaultExpandAll
            disabled={maxCount && result.length >= maxCount}
            selectedKeys={selectedKeys}
            expandedKeys={expandedKeys}
            onSelect={handleTreeSelect}
            onExpand={handleTreeExpand}
        >
            {getTreeNode(finalTree)}
        </Tree>
    );

    const menu = (
        <div className={styles.employeeSelectWrap}>
            <div className={styles.employeeSelect} onClick={e => e.stopPropagation()}>
                <div className={styles.employeeSelectLeft}>
                    <div className={styles.inputWrap}>
                        <Icon type="search" style={{ color: '#8C8C8C', fontSize: 18 }} />
                        <Input placeholder="搜索姓名" allowClear onChange={handleSearch} />
                    </div>
                    <div className={styles.selectMain}>
                        {tab === 3 ? (
                            <>
                                <div style={{ fontSize: 12, color: '#8C8C8C', padding: 16 }}>您可能想找</div>
                                <div className={styles.selectBox}>{renderRecent(searchList, '无搜索结果', true)}</div>
                            </>
                        ) : (
                            <>
                                <div className={styles.selectHead}>
                                    <span className={cn({ [styles.active]: tab === 1 })} onClick={() => setTab(1)}>
                                        最近
                                    </span>
                                    <span className={cn({ [styles.active]: tab === 2 })} onClick={() => setTab(2)}>
                                        组织架构
                                    </span>
                                </div>
                                <div className={styles.selectBox}>
                                    {tab === 1 ? renderRecent(recentList, '没有近期记录') : renderTree()}
                                </div>
                            </>
                        )}
                    </div>
                </div>
                <div className={styles.resultWrap}>
                    <div className={styles.resultHead}>
                        选择{title}{' '}
                        <span>
                            已选：{result.length}
                            {maxCount ? `/${maxCount}` : ''}
                        </span>
                    </div>
                    <div className={styles.resultMain}>
                        {result.map((item, index) => (
                            <div key={item.id} className={cn([styles.recentItem], { [styles.isGroup]: item.isGroup })}>
                                {!item.isGroup && <Avatar icon="user" style={{ marginRight: 6 }} />}
                                <div className={styles.recentName}>{item.employeeName || item.name}</div>
                                <Icon
                                    type="close-circle"
                                    theme="filled"
                                    style={{ color: '#BFBFBF', fontSize: 16 }}
                                    onClick={handleRemove(item, index)}
                                />
                            </div>
                        ))}
                    </div>
                </div>
            </div>
            <div
                className={styles.employeeSelectBtn}
                onClick={e => {
                    if (!hideRef.current) {
                        e.stopPropagation();
                    }
                    hideRef.current = false;
                }}
            >
                <Button style={{ marginRight: 12 }} onClick={handleCancel}>
                    取消
                </Button>
                <Button type="primary" onClick={handleOk}>
                    确定
                </Button>
            </div>
        </div>
    );

    return (
        <div>
            <Dropdown overlay={menu} trigger={['click']} onVisibleChange={handleVisibleChange}>
                <div className="ant-input" style={style}>
                    {placeholder && <span className={styles.placeholderStyle}>{placeholder}</span>}
                </div>
            </Dropdown>
        </div>
    );
};

EmployeeSelect.defaultProps = {
    placeholder: '请选择',
    maxCount: 1,
    onOk: () => {},
    onCancel: () => {}
};

export default EmployeeSelect;
